package com.ruoyi.web.controller.system;

import java.io.*;
import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.security.PermissionUtils;
import com.ruoyi.system.domain.Echarts;
import com.ruoyi.system.domain.StuData;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.StuCertificateMapper;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.StuCertificate;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 资格证书Controller
 * 
 * @author ruoyi
 * @date 2024-01-09
 */
@Controller
@RequestMapping("/system/certificate")
public class StuCertificateController extends BaseController
{
    private String prefix = "system/certificate";

    private Long nowUserId;
    private Long deptId;
    @Autowired
    private IStuCertificateService stuCertificateService;
    @Autowired
    private ISysDeptService deptService;
    private IStuDataService stuDataService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IStuDataCerService stuDataCerService;
    @Autowired
    private StuCertificateMapper stuCertificateMapper;

    @RequiresPermissions("system:certificate:view")
    @GetMapping()
    public String certificate()
    {
        return prefix + "/certificate";
    }

    /**
     * 查询资格证书列表
     */
    @RequiresPermissions("system:certificate:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StuCertificate stuCertificate)
    {
        startPage();
        // 获取当前用户ID和账号类型
        nowUserId = (Long) PermissionUtils.getPrincipalProperty("userId");
        deptId = (Long) PermissionUtils.getPrincipalProperty("deptId");
        List<StuCertificate> list;
        list = stuCertificateService.selectStuCertificateList(stuCertificate);
        return getDataTable(list);
    }

    /**
     * 导出资格证书列表
     */
    @RequiresPermissions("system:certificate:export")
    @Log(title = "资格证书", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(StuCertificate stuCertificate)
    {
        List<StuCertificate> list = stuCertificateService.selectStuCertificateList(stuCertificate);
        ExcelUtil<StuCertificate> util = new ExcelUtil<StuCertificate>(StuCertificate.class);
        return util.exportExcel(list, "资格证书数据");
    }

    /**
     * 新增资格证书
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存资格证书
     */
    @RequiresPermissions("system:certificate:add")
    @Log(title = "资格证书", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, StuCertificate stuCertificate) throws IOException
    {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        stuCertificate.setFilePath(fileName);
        stuCertificate.setUserId(nowUserId);
        stuCertificate.setDeptId(deptId);
        return toAjax(stuCertificateService.insertStuCertificate(stuCertificate));
    }

    /**
     * 修改资格证书
     */
    @RequiresPermissions("system:certificate:edit")
    @GetMapping("/edit/{cerId}")
    public String edit(@PathVariable("cerId") Long cerId, ModelMap mmap)
    {
        StuCertificate stuCertificate = stuCertificateService.selectStuCertificateByCerId(cerId);
        mmap.put("stuCertificate", stuCertificate);
        return prefix + "/edit";
    }

    /**
     * 修改保存资格证书
     */
    @RequiresPermissions("system:certificate:edit")
    @Log(title = "资格证书", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StuCertificate stuCertificate)
    {
        return toAjax(stuCertificateService.updateStuCertificate(stuCertificate));
    }

    /**
     * 修改资格证书文件
     */
    @PostMapping( "/editFile")
    @ResponseBody
    public AjaxResult editById(@RequestParam("file") MultipartFile file, StuCertificate stuCertificate) throws IOException
    {
        //删除原文件
        if(stuCertificate.getFilePath() != null){
            FileUtils.deleteFile(stuCertificate.getFilePath().replaceAll(Constants.RESOURCE_PREFIX, RuoYiConfig.getProfile()).replace("/", "\\"));
        }
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        stuCertificate.setFilePath(fileName);
        return toAjax(stuCertificateService.updateStuCertificate(stuCertificate));
    }

    /**
     * 删除资格证书
     */
    @RequiresPermissions("system:certificate:remove")
    @Log(title = "资格证书", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        //文件删除
        String[] array = Convert.toStrArray(ids);
        String deletePath;
        StuCertificate stuCertificate = new StuCertificate();
        for (int i = 0; i < array.length; i++) {
            deletePath = stuCertificateService.selectStuCertificateByCerId(Convert.toLong(array[i])).getFilePath();
            if( deletePath != null ){
                FileUtils.deleteFile(deletePath.replaceAll("/profile", RuoYiConfig.getProfile()).replace("/", "\\"));
                stuCertificate.setCerId(Convert.toLong(array[i]));
                stuCertificate.setFilePath("");
                stuCertificateService.updateStuCertificate(stuCertificate);
            }
        }
        //数据库删除
        //stuDataCerService.deleteStuDataCerByCerIds(ids);
        return toAjax(stuCertificateService.deleteStuCertificateByCerIds(ids));
    }

    /**
     * 删除资格证书文件
     */
    @PostMapping( "/remove/{cerId}")
    @ResponseBody
    public AjaxResult removeById(@PathVariable("cerId") Long cerId) throws IOException
    {
        StuCertificate stuCertificate = stuCertificateService.selectStuCertificateByCerId(cerId);
        //例如：将路径"/profile/upload/2024/02/26/0(4)_20240226092624A002.jpg"d的“/profile”替换成application.yml的profile
        FileUtils.deleteFile(stuCertificate.getFilePath().replaceAll(Constants.RESOURCE_PREFIX , RuoYiConfig.getProfile()).replace("/", "\\"));
        stuCertificate.setFilePath("");
        return toAjax(stuCertificateService.updateStuCertificate(stuCertificate));
    }

    @GetMapping("/upload/{cerId}")
    public String upload(@PathVariable("cerId") Long cerId, ModelMap mmap)
    {
        mmap.put("certificate", stuCertificateService.selectStuCertificateByCerId(cerId));
        return prefix + "/upload";
    }

    /**
     * 证书下载
     */
    @RequiresPermissions("system:certificate:download")
    @GetMapping("/download/resource")
    public void resourceDownload(String cerId, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        StuCertificate stuCertificate = stuCertificateService.selectStuCertificateByCerId(Convert.toLong(cerId));
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(stuCertificate.getFilePath(), Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, ".");
        downloadName =stuCertificate.getCerName() + "_" + stuCertificate.getStuNumber() + "_" + stuCertificate.getStuName() + "_" +  stuCertificate.getCerId() + "." + downloadName;
        //设置参数
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }


    /**
     * 批量下载
     */
    @RequiresPermissions("system:certificate:download")
    @GetMapping("/download/resources")
    public void downloadFiles(String cerIds, HttpServletRequest request, HttpServletResponse response){
        stuCertificateService.downloadFiles(cerIds, request,  response);
    }
//
//    /**
//     * 进入授权学生页
//     */
//    @RequiresPermissions("system:certificate:edit")
//    @GetMapping("/authStudentData/{cerId}")
//    public String authRole(@PathVariable("cerId") Long cerId, ModelMap mmap)
//    {
//        StuCertificate stuCertificate = stuCertificateService.selectStuCertificateByCerId(cerId);
//        mmap.put("stuCertificate", stuCertificate);
//        return prefix + "/authStudentData";
//    }
//
//    /**
//     * 查询已分配学生列表
//     */
//    @RequiresPermissions("system:certificate:list")
//    @PostMapping("/authStudentData/allocatedList")
//    @ResponseBody
//    public TableDataInfo allocatedList(StuData stuData)
//    {
//        startPage();
//        stuData.setUserId(nowUserId);
//        List<StuData> list = stuDataService.selectAllocatedList(stuData);
//        return getDataTable(list);
//    }
//
//    /**
//     * 取消授权
//     */
//    @RequiresPermissions("system:certificate:edit")
//    @Log(title = "学生管理", businessType = BusinessType.GRANT)
//    @PostMapping("/authStudentData/cancel")
//    @ResponseBody
//    public AjaxResult cancelAuthStuData(StuCertificate stuCertificate)
//    {
//        StuData stuData = new StuData();
//        stuData.setCerId(stuCertificate.getCerId());
//        //事实上是update
//        return toAjax(stuDataService.deleteAuthStudentData(stuData));
//    }

    /**
     * 证书预览
     */
    @RequiresPermissions("system:certificate:pdfView")
    @GetMapping("/pdfView/{cerId}")
    public String pdfView(@PathVariable("cerId") Long cerId, ModelMap mmap)
    {
        StuCertificate stuCertificate = stuCertificateService.selectStuCertificateByCerId(cerId);
        mmap.put("stuCertificate", stuCertificate);
        return prefix + "/pdfView";
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/deptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData()
    {
        List<Ztree> ztrees = deptService.selectDeptTree(new SysDept());
        return ztrees;
    }

    @GetMapping("/echarts1")
    public String Echarts()
    {
        return prefix + "/echarts1";
    }
    @PostMapping("/echarts1/{deptId}")
    @ResponseBody
    public Object pieEcharts(@PathVariable("deptId") Long deptId)throws Exception
    {
        StuCertificate stuCertificate = new StuCertificate();
        stuCertificate.setDeptId(deptId);
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Echarts> varList = stuCertificateService.IsExpiredCount(stuCertificate);
        ArrayList<Object> list = new ArrayList<>();
        ArrayList<Object> arrayList = new ArrayList<>();
        for (Echarts echarts : varList) {
            HashMap<Object, Object> hashMap = new HashMap<>();
            String name = echarts.getName();
            list.add(name);
            int value = echarts.getValue();
            hashMap.put("name",name);
            hashMap.put("value",value);
            arrayList.add(hashMap);
        }
        map.put("list",list);

        map.put("varList",arrayList);
        return map;
    }
}
